package com.example.Gethome.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.HttpURLConnection;
import java.util.Random;

public class SendMSNMessage {
    public String getCheckCode() {
        Random random = new Random();
        int checkCode = random.nextInt(900000) + 100000;
        return checkCode + "";
    }

    public boolean sendSMSMessage(
            String mobile,
            String checkCode){
        String url = "https://api.binstd.com/sms/send";
        // todo 在这里编辑经审核的短信模板.
        String param = "mobile=" + mobile + "&content=您的手机验证码为"+ checkCode +"，5分钟内有效。请不要把此验证码泄露给任何人。【MBRY】&appkey=16e666a737db0889";
        sendHttpRequest(url, param);
        return true;
    }

    public void sendHttpRequest(String url, String param) {
        String result = "";
        BufferedReader in = null;
        HttpURLConnection conn = null;
        try {
            String urlNameString = url + "?" +param;
            URL realUrl = new URL(urlNameString);
            conn = (HttpURLConnection) realUrl.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(15000);
            conn.setReadTimeout(60000);
            conn.setRequestProperty("Accept", "application/json");
            conn.connect();
            if(200 == conn.getResponseCode()) {
                in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
            }
        } catch (Exception e) {
            System.err.println("GET请求出现404错误!" + e);
            e.printStackTrace();
        }
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        System.out.println(result);
    }
}
